use axum::{Json, Router};
use axum::routing::get;
use tower_cookies::Cookies;

use crate::models::{AttachedUser, User};
use crate::utils::cookie;

type RouterResult<T> = Result<T,String>;

pub mod guide;
pub mod communication;
pub mod module_recom;
pub mod image_share;
// struct RouterResponse {

// }

pub fn router() -> Router {
    Router::new()
        .route("/", get(index))
        .nest("/guide", guide::router())
        .nest("/communication", communication::router())
        .nest("/module_recom", module_recom::router())
        .nest("/image_share", image_share::router())
        .route("/get_current_user",get(get_current_user))
        .route("/get_current_user_complete",get(get_current_user_complete))
}

async fn index(cookies:Cookies) -> RouterResult<String> {
    let user_id = cookie::get_user_id_from_cookie(cookies).unwrap();

    let user_id: i32 = user_id.parse().unwrap();

    let user = User::fetch_one_by_id(user_id).await.map_err(|err| err.to_string())?;

    Ok(format!("欢迎来到特权区域，{}！",user.nickname))

}

/// 返回当前登录的用户
async fn get_current_user(cookies:Cookies) -> Json<AttachedUser>{
    let user = cookie::get_user_from_cookies(cookies).await.unwrap();
    let image = user.get_user_image().await.unwrap();
    let attach_user = AttachedUser{
        id: user.id,
        nickname: user.nickname,
        image
    };
    return Json(attach_user);
}
async fn get_current_user_complete(cookies:Cookies) -> Json<User>{
    let user = cookie::get_user_from_cookies(cookies).await.unwrap();
    return Json(user);
}